//
//  QHTableSubViewController.m
//  QHTableViewDemo
//
//  Created by chen on 17/3/21.
//  Copyright © 2017年 chen. All rights reserved.
//

#import "QHTableSubViewController.h"

#import "QHAVFVideoCapture.h"
#import "QHMediaUtil.h"
#import "simplest_eagl_rgb_render.h"

#define kMediaCaptureQueue @"com.qh.media.captureQueue"

@interface QHTableSubViewController ()

@property (nonatomic, strong) QHAVFVideoCapture *vCap;

@property (nonatomic) dispatch_queue_t capQueue;
@property (nonatomic, strong) NSLock *quitLock;

@property (nonatomic, strong, nullable) UIView *preview;
@property (nonatomic, strong) NSString *vCapPreset;

@property (nonatomic, strong) simplest_eagl_rgb_render *render;
@property (nonatomic) int type;

@end

@implementation QHTableSubViewController

- (void)viewWillDisappear:(BOOL)animated {
    if (self.navigationController.topViewController != self) {
        [self closeKit];
    }
}

- (instancetype)initWith:(int)type {
    self = [super init];
    if (self) {
        self.type = type;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self p_setup];
    [self startPreview:self.view];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)closeKit {
    [_vCap stop];
}

- (void)startPreview:(UIView *)v {
    if (_capQueue == nil || v == nil || _vCap.isRunnig) {
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^(){
//        if (self.preview == nil) {
//            self.preview = [UIView new];
//        }
//        [v addSubview:self.preview];
//        [v sendSubviewToBack:self.preview];
        if ([self p_startVideoCap] == NO){
            return;
        }
    });
}

- (void)stopPreview {
    if (_vCap == nil ) {
        return;
    }
    [self newCaptureState:0];
    dispatch_async(self.capQueue, ^{
        [self.quitLock lock];
        [self closeKit];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.preview) {
                [self.preview removeFromSuperview];
                self.preview = nil;
            }
        });
        [self.quitLock unlock];
        [self newCaptureState:1];
    });
}

#pragma mark - Private

- (void)p_setup {
    _capQueue = dispatch_queue_create([kMediaCaptureQueue cStringUsingEncoding:NSASCIIStringEncoding], DISPATCH_QUEUE_SERIAL);
    _quitLock = [NSLock new];
    
    _vCapPreset = AVCaptureSessionPresetiFrame960x540;
    
    _vCap = [[QHAVFVideoCapture alloc] initWith:self.vCapPreset cameraPosition:AVCaptureDevicePositionBack];
    if(_vCap == nil) {
        return;
    }
    _preview = [UIView new];
    _preview.clipsToBounds = YES;
    UIView *v = self.view;
    CGRect rect = [UIScreen mainScreen].bounds;
    CGFloat x = 30;
    CGFloat w = rect.size.width - x * 2;
    CGFloat h = w / 9.f * 16.f;
    CGFloat y = (rect.size.height - h) / 2.f;
    self.preview.frame = CGRectMake(x, y, w, h);
    [v addSubview:self.preview];
    [v sendSubviewToBack:self.preview];
    
    self.render = [simplest_eagl_rgb_render createWith:self.preview type:self.type];
    
    [self p_setupVideoPath];
    [self.render addWbImage];
}

- (void)p_setupVideoPath {
    weakObj(self);
    self.vCap.vProcessingCallback = ^(CMSampleBufferRef  _Nonnull sampleBuffer) {
        strongObj(selfWeak);
        [selfWeakStrong.render processSampleBuffer:sampleBuffer];
    };
    self.vCap.vInterruptCallback = ^(BOOL bInterrupt) {
        
    };
}

- (BOOL)p_startVideoCap {
    AVAuthorizationStatus status_video = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status_video == AVAuthorizationStatusDenied) {
        [self newCaptureState:-1];
        return NO;
    }
    if (self.vCapPreset == nil) {
        [self newCaptureState:-2];
        return NO;
    }
    dispatch_async(self.capQueue, ^{
        [self.quitLock lock];
        self.vCap.vPreset = self.vCapPreset;
        // check if preset ok
        self.vCapPreset = self.vCap.vPreset;
        [self.vCap start];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self.preview.layer addSublayer:self.vCap.previewLayer];
//            self.vCap.previewLayer.frame = self.preview.bounds;
//        });
        [self.quitLock unlock];
        [self newCaptureState:3];
    });
    return YES;
}

#pragma mark - Action

- (void)newCaptureState:(int)state {
    dispatch_async(dispatch_get_main_queue(), ^{
//        self.capState = state;
    });
}

@end
